#生成一个类，用于发布消息
import json
import paho.mqtt.client as mqtt_client

# 车辆上报主题
topicBattery = "vehicle/home1/telemetry/battery"
topicSpeed = "vehicle/home1/telemetry/speed"
topicAlarm = "vehicle/home1/telemetry/alarm"

class Report:
    def __init__(self, client: mqtt_client):
        self.client = client

    def reportBattery(self, battery_level: int):
        msg = json.dumps({"battery_level": battery_level})
        result = self.client.publish(topicBattery, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topicBattery}`")
        else:
            print(f"Failed to send message to topic {topicBattery}")

    def reportSpeed(self, speed: int):
        msg = json.dumps({"speed": speed})
        #self.client.loop_start()
        result = self.client.publish(topicSpeed, msg)
        #self.client.loop_stop()
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topicSpeed}`")
        else:
            print(f"Failed to send message to topic {topicSpeed}")

    def reportAlarm(self, alarm: bool):
        msg = json.dumps({"alarm": alarm})
        result = self.client.publish(topicAlarm, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topicAlarm}`")
        else:
            print(f"Failed to send message to topic {topicAlarm}")
